package cn.tedu.egweibo1.controller;

import cn.tedu.egweibo1.mapper.UserMapper;
import cn.tedu.egweibo1.pojo.dto.UserRegDTO;
import cn.tedu.egweibo1.pojo.entity.User;
import cn.tedu.egweibo1.pojo.vo.UserRegVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/v2/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("reg")
    public int reg(@RequestBody UserRegDTO userRegDTO){
        String username = userRegDTO.getUsername();
        UserRegVO userRegVO = userMapper.selectByUsername(username);
        if (userRegVO!=null){
            return 2;
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO ,user);
        userMapper.insert(user);
        return 1;
    }
    @PostMapping("login")
    public int login(@RequestBody UserRegDTO userRegDTO, HttpSession session){
        String username = userRegDTO.getUsername();
        UserRegVO userRegVO = userMapper.selectByUsername(username);
        if (userRegVO==null){
            return 3;
        }
        if (userRegVO.getPassword().equals(userRegDTO.getPassword())){
            session.setAttribute("user",userRegVO);
            return 1;
        }
        return 2;
    }
    @GetMapping("currentUser")
    public UserRegVO currentUser(HttpSession session){
        UserRegVO user = (UserRegVO) session.getAttribute("user");
        return user;
    }
    @GetMapping("logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }
}
